var koa = require('koa');
var app = koa();
var config = require('./config/config.js');

// ---logger
app.use(function*(next) {
    console.log('%s', this.method, this.url);
    var start = new Date();
    yield next;
    var ms = new Date() - start;
    console.log('%s %s - %s', this.method, this.url, ms);
});


// ---session
var session = require('koa-session');
app.keys = ['hello-world'];
app.use(session(app));


// ---enable cross domain
app.use(function*(next) {
    this.set("Access-Control-Allow-Origin", "*");
    this.set("Access-Control-Allow-Methods", "*");
    this.set("Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept");
    if (this.method === 'OPTION') {
        this.body = "Access-Control-Allow-Origin";
    } else {
        yield next;
    }
});


// ---body parser
var bodyParser = require('koa-body-parser');
app.use(bodyParser());

// static folder
var serve = require('koa-static');
// app.use(serve(__dirname + '/public/html'));
app.use(serve(__dirname + '/public'));
// app.use(serve(__dirname + '/public/js'));
// app.use(serve(__dirname + '/public/css'));


// -------load all router in path
// TODO 
console.log('----load router-----');
app.use(require('./router/api/all.js'));
app.use(require('./router/api/logstash.js'));
var fs = require('fs');
var path = require('path');
var routerDir = path.join(__dirname, 'router/api/v2');
var routerFileList = fs.readdirSync(routerDir);
routerFileList.sort();
// get all file
routerFileList.forEach(function (item) {
    var routerPath = path.join(routerDir, item);
    var stats = fs.lstatSync(routerPath);
    if (stats.isFile()) {
        var aRouter = require(routerPath);
        if (aRouter) {
            app.use(aRouter);
        }
    }
});
console.log('----load router done-----');

// 404
app.use(function*() {
    this.status = 404;
    this.body = '404 not found';
});


app.listen(config.httpPort, function () {
    console.log('server listen at ' + config.httpPort);
});